<!-- 
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-07-30 20:02:30
 * @LastEditTime: 2020-02-28 11:25:38
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>Hello APP</title>
    <link rel="stylesheet" type="text/css" href="../css/vant.css">
    <link rel="stylesheet" type="text/css" href="../css/base.css" />
    <script type="text/javascript" src="../script/jquery.js"></script>
    <script type="text/javascript" src="../script/layer/mobile/layer.js"></script>
    <script type="text/javascript" src="../script/vue.min.js"></script>
    <script type="text/javascript" src="../script/vant.min.js"></script>
    <script type="text/javascript" src="../script/fastclick.js"></script>
    <script type="text/javascript" src="../script/base.js"></script>
    <script type="text/javascript" src="../script/scanTransf.js"></script>
    <style type="text/css">
        .train-time-block {
            margin: 15px 0;
            padding: 12px 0;
            text-align: center;
        }

        .train-title {
            color: #e6c678;
            font-weight: bold;
            margin-bottom: 12px;
            font-size: 15px;
        }

        .train-btn-row {
            display: flex;
            justify-content: space-around;
            margin-bottom: 10px;
        }

        .train-btn-row .van-button {
            width: 42%;
            font-weight: 500;
        }

        .box {
            width: 100%;
            display: flex;
            flex-direction: column;
        }

        .form {
            width: 100%;
            height: auto;
        }

        .content {
            padding: 0 50px;
        }

        .van-field {
            width: 33.33%;
            float: left;
        }

        .van-cell {
            background-color: transparent;
        }

        .van-field__control {
            border-bottom: 2px solid #e6c678;
        }

        .van-cell::after {
            border-bottom: 0;
        }

        .btns {
            width: 100%;
            display: flex;
            margin-top: 10px;
            padding-bottom: 10px;
        }

        .leftBtn {
            width: 50%;
        }

        .leftBtn .van-button {
            width: 60%;
            height: 100px;
        }

        .rightBtn {
            width: 50%;
        }

        .rightBtn .van-button:first-child {
            margin-bottom: 10px;
        }

        .devicePop {
            height: 50%;
            overflow: auto;
        }

        .devicePop .van-col {
            padding: 5px 8px;
            text-align: center;
        }

        .devicePop .van-col .van-button {
            width: 100%;
        }

        .editBtn {
            vertical-align: middle;
            float: right;
            padding: 3px 2px;
        }

        .bottom {
            padding: 0 50px;
            padding-top: 10px;
        }

        .bottom .van-button {
            margin-right: 10px;
        }

        .van-field__control {
            color: #fff;
            text-align: center;
        }

        .baoZhangPOP {
            padding: 20px;
            width: 300px;
            height: 150px;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
        }

        .baoZhangPOP .van-field {
            width: 100%;
        }

        .baoZhangPOP .van-field__control {
            color: #000;
        }

        .baoZhangPOP .van-button {
            margin: auto;
            padding: 10px;
        }

        .top {
            width: 100%;
            padding-top: 5px;
            display: flex;
        }

        .topLeft {
            width: 70%;
            padding-left: 50px;
        }

        .topRight {
            width: 30%;
            text-align: right;
            padding-right: 5px;
        }

        .topMiddle {
            width: 40%;
            text-align: center;

        }


        .van-icon-arrow-left {
            position: absolute;
            top: 150px;
            right: 0;
            font-size: 20px;
            font-weight: 700;
            z-index: 999999;
        }

        .boxListPOP {
            width: 60%;
            height: 100%;
            background-color: #212022;
            color: #fff;
            border: 1px solid #e6c678;
        }

        .boxListBox {
            width: 100%;
            height: 100%;
            overflow-y: auto;
        }

        .boxListPOP .van-field {
            width: 100%;
        }

        .table table tr td .van-checkbox__icon--square {
            margin: auto;
        }

        .boxListPOP .boxDelete {
            width: 100%;
            display: flex;
        }

        .boxDelete .van-button {
            width: 30%;
            margin: auto;
            margin-left: 10px;
        }

        .boxDelete .van-field {
            width: 70%;
            margin: auto;
        }

        .back {
            padding: 10px 20px;
        }

        .editNum {
            padding: 10px 20px;
        }

        .printMsg {
            width: 150px;
            height: 150px;
            border-radius: 10px;
            background-color: rgba(0, 0, 0, 0.7);
        }

        .loadingPrint {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .loadingPrint .van-loading {
            height: 70%;
            width: 100%;
            margin: auto;
            margin-top: 20px;
        }

        .loadingPrint .van-button {
            width: 85%;
            margin: auto;
            margin-bottom: 20px;
        }

        input {
            width: 70%;
            color: #fff;
            background: none;
            outline: none;
            border: none;
        }

        .printBtn {
            padding-top: 10px;
            display: flex;
        }

        .van-radio-group {
            padding: 4px 20px;
            justify-content: space-between;
        }

        .tableScroll {
            height: 100%;
            overflow-y: scroll;
        }

        .approvePop {
            background-color: #212022;
            box-sizing: border-box;
            padding: 20px 30px;
            width: 100%;
            height: 60vh;
        }

        .approvePop .van-field {
            width: 100%;
        }

        .approvePop .approveBtns {
            position: absolute;
            bottom: 0;
            width: 100%;
            box-sizing: border-box;
            display: flex;
        }

        .approvePop .approveBtns .van-button {
            width: 60%;
            margin: auto;
        }

        .scanPop {
            width: 160px;
            height: 180px;
            text-align: center;
            background-color: transparent;
            margin: 0;
            padding: 0;
        }

        .van-icon-enlarge {
            font-size: 150px;
            color: #e6c678;
            margin: 0;
            padding: 0;
        }

        .inputClass {
            opacity: 0;
            width: 150px;
        }

        .scanLine {
            position: absolute;
            z-index: 2;
            width: 66%;
            height: 2px;
            transform: translateX(25%);
            background-color: #e6c678;
            animation: scanLineMove 2s infinite;
        }

        .newClass {
            color: red;
        }

        @keyframes scanLineMove {
            from {
                top: 30px;
            }

            to {
                top: 120px;
            }
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <div class="box">
            <div class="top">
                <div class="topLeft">
                    <van-field v-if="!TY" v-model="formData.beforeEquipment" label="注塑设备：" readonly
                        @click="openBaseScreen('机台')"></van-field>
                    <van-field v-if="!TY" v-model="formData.beforeBatch" label="注塑批次："></van-field>
                    <van-button v-show="showPrintControls && !clockInShow"
                        :color="autoPrintEnabled ? '#ff0000' : '#00ff00'" type="primary" @click="toggleAutoPrint">
                        {{ autoPrintEnabled ? '关闭自动打印' : '开启自动打印' }}

                    </van-button>
                </div>


                <div class="topRight">

                    <van-button v-if="!TY" color="linear-gradient(#fffeaa, #c07d39)" icon="scan" type="primary"
                        size="small" @click="openScan">
                        切换注塑箱码</van-button>
                    </van-button>

                    <van-button v-if="formData.empl === '严之鉴'"
                        :color="realAutoPrintStatus === 1 ? 'linear-gradient(#ff0000, #800000)' : 'linear-gradient(#00ff00, #008000)'"
                        type="primary" size="small" @click="handleForceDisableAutoPrint">
                        {{ realAutoPrintStatus === 1 ? '关闭' : '开启' }}
                    </van-button>

                    <van-button v-if="formData.empl === '张银'" class="editNum" color="linear-gradient(#fffeaa, #c07d39)"
                        type="primary" size="mini" @click="handlerQualityReprint">
                        补打标签（品质）
                    </van-button>
                    <van-button class="editNum" v-if="TY && showPrintControls && !clockInShow && !autoPrintEnabled"
                        color="linear-gradient(#fffeaa, #c07d39)" type="primary" size="mini"
                        @click="showTotalPrint = true">批量打印</van-button>
                    </van-button>

                    <van-button class="editNum" v-show="monitorEdit" color="linear-gradient(#fffeaa, #c07d39)"
                        type="primary" size="mini" @click="editBaoZhang()">修改包装数量
                    </van-button>

                </div>
                <van-icon name="arrow-left" color="#e6c678" v-show="!showBoxList" @click="arrowLeftClick"></van-icon>
            </div>

            <div class="content">
                <div class="form">
                    <van-field v-model="formData.EquipmentCode" label="机台编号：" readonly></van-field>
                    <van-field v-model="formData.reportID" label="报工ID：" readonly></van-field>
                    <van-field v-model="formData.PlanFinsh" label="预计完成：" readonly></van-field>
                    <van-field v-model="formData.empl" label="操作人：" readonly></van-field>
                    <van-field v-show="TY" v-model="formData.startTime" label="上机时间：" readonly></van-field>
                    <van-field v-show="TY" v-model="formData.endTime" label="下机时间：" readonly></van-field>
                    <van-field v-model="formData.ZhuSuPlanID" label="计划单号：" readonly></van-field>
                    <van-field v-model="formData.ProductionNO" label="生产订单：" readonly></van-field>
                    <van-field v-model="formData.Batch" label="批次号：" readonly></van-field>
                    <!-- <div class="topMiddle"> -->
                    <!-- <van-field v-model="QuantitySS" label="累计生产数量：" @click="openEditQuantitySSPopup"></van-field> -->
                    <van-field v-model="QuantitySS" label="累计生产数量：" readonly>
                        <template #button>
                            <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)"
                                @click="openEditQuantitySSPopup">修改</van-button>
                        </template>
                    </van-field>
                    <van-field v-model="ALBarCodeNum" label="已打印标签数："></van-field>
                    <van-field v-model="QuantityAlPrint" label="实时生产数量："></van-field>
                    <!-- </div> -->
                </div>
                <div class="table">
                    <table>
                        <tr>
                            <th>序号</th>
                            <th>工单</th>
                            <th>产品编码</th>
                            <th>产品名称</th>
                            <th>产品规格</th>
                            <th>包装数量</th>
                            <th>订单数量</th>
                            <th>订单欠数</th>
                        </tr>
                        <tbody v-for="(item, index) in tableData">
                            <tr>
                                <td>{{item.number}}</td>
                                <td>{{item.MONO ? item.MONO : '暂无数据'}}</td>
                                <td>{{item.ProductCode}}</td>
                                <td>{{item.ProductName}}
                                    <van-button class="editBtn" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                                        size="mini" @click="handlerESOP(item, index)">ESOP查看
                                    </van-button>
                                </td>
                                <td>{{item.ProductSpec ? item.ProductSpec : '暂无数据'}}</td>
                                <td>{{item.BaoZhangQTY}}
                                    <van-button class="editBtn" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                                        size="mini" @click="editBaoZhang(item, index)">修改
                                    </van-button>
                                </td>
                                <td>{{item.PlanQTY1}}</td>
                                <td>{{item.PlanQianQTY}}</td>
                            </tr>
                        </tbody>

                    </table>
                </div>
            </div>
            <div class="bottom">
                <van-button v-show="showPrintControls && !clockInShow && !autoPrintEnabled"
                    color="linear-gradient(#fffeaa, #c07d39)" type="primary" block :disabled="ifConfirm1"
                    :loading="ifConfirm1" loading-text="正在打印..." @click="printCode1('序号1')">
                    序号1打印
                </van-button>
                <van-button v-show="showPrintControls && showBtn2 && !autoPrintEnabled"
                    color="linear-gradient(#fffeaa, #c07d39)" type="primary" block :disabled="ifConfirm2"
                    :loading="ifConfirm2" loading-text="正在打印..." @click="printCode2('序号2')">
                    序号2打印
                </van-button>
                <van-button v-show="!clockInShow" color="linear-gradient(#fffeaa, #c07d39)" type="primary" block
                    @click="clockOut">下机打卡</van-button>
                <van-button v-show="!clockInShow" color="#ff0000" type="primary" block @click='handlerBadReason'>不良报废
                </van-button>
                <van-button v-show="!clockInShow" color="#ffa500" type="primary" block @click="arrowLeftClick">标签作废
                </van-button>
                <van-button v-show="!clockInShow" color="#ff0000" type="primary" block @click="toBroke">故障呼叫
                </van-button>
            </div>

            <!-- <van-popup v-model="showEditQuantitySSPopup" class="baoZhangPOP">
                 <van-field v-model="editQuantitySS" label="修正累计生产数量" placeholder="请输入修正值"></van-field>
                 <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                     @click="confirmEditQuantitySS">
                     确认
                 </van-button>
             </van-popup> -->
            <van-popup v-model="showEditQuantitySSPopup" class="baoZhangPOP">
                <van-field v-model="editQuantitySS" label="修正累计生产数量" placeholder="请输入修正值" type="number"></van-field>
                <div class="printBtn">
                    <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)" @click="confirmEditQuantitySS">确认
                    </van-button>
                    <van-button size="mini" color="#999" @click="showEditQuantitySSPopup = false">取消</van-button>
                </div>
            </van-popup>

            <van-popup v-model="showPrintMsg" class="printMsg" :close-on-click-overlay="false">
                <div class="loadingPrint">
                    <van-loading size="30px" color="#fffeaa" vertical>{{printMsg}}</van-loading>
                    <van-button size="small" color="linear-gradient(#fffeaa, #c07d39)" type="primary" block
                        @click="cancelPrint">
                        取消打印
                    </van-button>
                </div>
            </van-popup>

            <van-popup v-model="showEditBaoZhang" class="baoZhangPOP">
                <van-field v-model="editBaoZhangQTY" label="包装数量" placeholder="填写包装数量"></van-field>
                <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                    @click="confirmBaoZhangQTY">确认</van-button>
            </van-popup>

            <van-popup v-model="showTotalPrint" class="baoZhangPOP">
                <van-radio-group v-model="radio" direction="horizontal">
                    <van-radio name="1" checked-color="#e6c678">序号1</van-radio>
                    <van-radio v-show="showBtn2" name="2" checked-color="#e6c678">序号2</van-radio>
                </van-radio-group>
                <van-field v-model="totalPrint" label="批量打印(<5)" placeholder="批量打印数量必须小于5"></van-field>
                <div class="printBtn">
                    <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                        @click="confirmTotalPrint">确认</van-button>
                    <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                        @click="showTotalPrint = false">取消</van-button>
                </div>
            </van-popup>

            <van-popup class="boxListPOP" v-model="showBoxList" position="right">
                <div class="boxListBox">
                    <div class="boxDelete">
                        <van-button icon="delete" type="primary" size="mini" color="linear-gradient(#fffeaa, #c07d39)"
                            @click="handlerDeleteBox">
                            作废标签
                        </van-button>
                        <van-button icon="printer" type="primary" size="mini" color="linear-gradient(#fffeaa, #c07d39)"
                            @click="handlerPrintAgain">
                            补打标签
                        </van-button>
                        <van-field v-model="boxListTotal" label="合计报工总数：" placeholder="暂无数据"></van-field>
                    </div>
                    <div class="table tableScroll">
                        <table>
                            <tr>
                                <th>操作</th>
                                <th>时间</th>
                                <th>箱码</th>
                                <th>批次</th>
                                <th>本箱序号</th>
                                <th>数量</th>
                            </tr>
                            <tr v-for="item in boxList">
                                <td>
                                    <van-checkbox v-model="item.checked" checked-color="#e6c678" shape="square"
                                        @change="boxListChange(item)">
                                    </van-checkbox>
                                </td>
                                <td>{{item.ReporTime}}</td>
                                <td>{{item.FBoxCode}}</td>
                                <td>{{item.Batch}}</td>
                                <td>{{item.FBoxNum}}</td>
                                <td>{{item.ReporQTY}}</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </van-popup>

            <van-popup class="approvePop" v-model="trainShow" closeable close-icon="close" position="bottom"
                :close-on-click-overlay="false">
                <van-field v-model="trainData.trainFlag" label="是否岗前培训" placeholder="请输入是否岗前培训"></van-field>
                <van-field v-model="trainData.PXName" label="培训人" placeholder="请输入培训人" @click="handlerPXName" required
                    readonly is-link>
                </van-field>

                <!-- 新增：培训时间记录 - 垂直布局 -->
                <!-- 新增：培训时间记录 -->
                <div class="train-time-block">
                    <div class="train-title">培训时间记录</div>

                    <!-- 按钮行 -->
                    <div class="train-btn-row">
                        <van-button round size="small" color="linear-gradient(135deg, #fffeaa 0%, #c07d39 100%)"
                            icon="play-circle-o" @click="recordTrainingTime('start')">开始培训</van-button>

                        <van-button round size="small" color="linear-gradient(135deg, #00c853 0%, #64dd17 100%)"
                            icon="checked" :disabled="!trainData.startTime" @click="recordTrainingTime('end')">结束培训
                        </van-button>
                    </div>

                    <!-- 时间显示 -->
                    <van-field v-model="trainData.startTime" label="开始时间" readonly placeholder="未记录" />
                    <van-field v-model="trainData.endTime" label="结束时间" readonly placeholder="未记录" />
                </div>

                <div class="approveBtns">
                    <van-button type="info" color="linear-gradient(#fffeaa, #c07d39)" @click="handlerTrain">确认
                    </van-button>
                </div>
            </van-popup>

            <van-popup v-model="scanShow" class="scanPop">
                <div class="scanLine"></div>
                <van-icon name="enlarge"></van-icon>
                <input type="number" class="inputClass" id="autoInput" autofocus ref="input"
                    @onkeyup="inputFocus(event)"></input>
            </van-popup>
            <!-- 品质补打弹窗 -->
            <van-popup v-model="qualityReprintShow" class="baoZhangPOP">
                <van-field v-model="qualityReprintCode" label="箱码" placeholder="请输入箱码（自动格式化）"
                    @input="formatQualityCode">
                </van-field>
                <div class="printBtn">
                    <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                        @click="confirmQualityReprint">
                        确认补打
                    </van-button>
                    <van-button size="mini" color="linear-gradient(#fffeaa, #c07d39)" type="primary"
                        @click="qualityReprintShow = false">
                        取消
                    </van-button>
                </div>
            </van-popup>

            <!-- <van-popup v-model="scanShow" class="scanPop">
                   <div class="scanLine"></div>
                   <van-icon name="enlarge"></van-icon>
                   <input id="autoInput" class="inputClass" type="text" v-model="inputCode" ref="input" autofocus
                       @keyup.enter="inputFocus()">
               </van-popup> -->
        </div>
    </div>
    </div>
</body>

<script type="text/javascript">
    var vm;
    apiready = function () {

        var escPrinter = api.require('escPrinter');
        var scanS60A = api.require('ScanS60A');

        api.addEventListener({
            name: 'refreshDeviceBroke'
        }, function (ret, err) {
            vm.getDataList();
        })
        api.addEventListener({
            name: 'selectRow'
        }, function (ret, err) {
            var type = ret.value.type;
            var row = ret.value.row;
            if (type == '机台') {
                vm.formData.beforeEquipment = row.EquipmentName;
            }
        })

        api.addEventListener({
            name: 'refreshProductReport'
        }, function (ret) {
            vm.showPrintMsg = false
            vm.showBoxList = false
            vm.showTotalPrint = false

            vm.ifConfirm1 = false
            vm.ifConfirm2 = false

            vm.totalPrint = ''

            if (ret.value.err) {
                api.sendEvent({
                    name: 'setPrint',
                })
            } else {
                vm.getList()
                vm.getBoxList()
            }
        })

        //     api.addEventListener({
        //     name: 'viewunload'          // 
        // }, function () {
        //     vm.stopAutoPrintInterval(); //
        //     vm.autoPrintEnabled = false;//
        //     console.log('【自动打印】页面卸载，定时器已销毁');
        // });
        // api.addEventListener({
        //     name: 'escPrinterBack'
        // }, function (ret) {
        //     var ok = ret.value.result === 0;
        //     if (vm.printCB) {
        //         vm.printCB(ok);   // 通知当前任务
        //     }
        // });
        vm = new Vue({
            el: '#app',
            data: {
                formData: {
                    EquipmentCode: '',
                    reportID: '',
                    PlanFinsh: '',
                    empl: '',
                    startTime: '',
                    endTime: '',
                    ZhuSuPlanID: api.pageParam.ZhuSuPlanID,
                    ProductionNO: '',
                    Batch: '',
                    WhetherStarteEquipment: '',
                    ZhuSuPlanNO: '',
                    beforeBatch: '',
                    beforeEquipment: ''
                },
                tableData: [
                    {
                        number: 1,
                        MONO: '',
                        ProductCode: '',
                        ProductID: '',
                        ProductName: '',
                        ProductSpec: '',
                        BaoZhangQTY: '',
                        PlanQTY1: '',
                        PlanQianQTY: '',
                    },
                ],
                planList: [],
                innerList: [],
                showEditBaoZhang: false,
                editBaoZhangQTY: '',
                currerntEdit: {},
                initialHeight: '',
                clockInShow: true,
                monitorEdit: api.pageParam.roleName == '组长' || api.pageParam.roleName == '管理员',
                showBoxList: false,
                boxList: [],
                boxListTotal: '',
                canEditQty: false,
                boxListDelete: [],
                printQueue: [],
                currentPrinting: null,
                currentIndex: '',
                totalQtys: 0,
                totalQtys2: 0,
                showBtn2: false,
                showPrintMsg: false,
                qualityReprintShow: false,
                qualityReprintCode: '',
                currentBtn: '',
                printMsg: '',
                showTotalPrint: false,
                totalPrint: '',
                radio: '1',
                TY: api.pageParam.equipment.EquipmentName.indexOf('涂油') == -1, //不是涂油
                ifConfirm1: false,
                ifConfirm2: false,
                trainShow: false,
                printStep: 0,
                SSHM: '',
                QSHM: '',
                XS: 0,
                canEditQty: false,
                QuantitySS: 0,
                QuantityAlPrint: 0,
                ALBarCodeNum: 0,
                currentTrainingAction: null,
                ALBarCodeNum2: 0,
                scrappedQuantity: 0,
                BadProductsTotal: 0,
                tnumber1: 0,
                tnumber2: 0,
                fnumber1: 0,
                QSHM2: 0,
                intervalId: null,
                showEditQuantitySSPopup: false, // 
                isBoxListOpen: false,
                editQuantitySS: 0, //
                correctedQuantitySS: 0, // 
                autoPrintEnabled: false,
                forceAutoPrint: false,
                showPrintControls: true,
                realAutoPrintStatus: 0,
                trainData: {
                    trainFlag: '已岗前培训',
                    PXName: '',
                    FRemarks: '',
                    startTime: '', // 新增：培训开始时间
                    endTime: ''    // 新增：培训结束时间
                },
                scanShow: false,
                inputCode: '',
                pairPrinting: false,   // 是否正在成对打印
                pairSide: 1,           // 1-左边 2-右边
            },
            watch: {
                showBoxList: function (newVal) {
                    if (!newVal && this.isBoxListOpen) {
                        this.isBoxListOpen = false;
                        if (this.autoPrintEnabled) {
                            this.startAutoPrintInterval();
                            vm.$toast('自动打印已恢复');
                        }
                    }
                }
            },

            created: function () {
                this.enterTime = Date.now()
                var that = this

                // console.log('PAD' + JSON.stringify(api.deviceModel))
                // console.log('pageParam' + JSON.stringify(api.pageParam))
                // console.log('choosePlan' + JSON.stringify(api.pageParam.choosePlan))

                if (window.localStorage.getItem('clientHeight') != 752) {
                    document.getElementById('app').style.zoom = 0
                } else {
                    document.getElementById('app').style.zoom = 1.5
                }

                that.initialHeight = api.frameHeight
                if (api.pageParam.equipment) {
                    that.formData.EquipmentCode = api.pageParam.equipment.EquipmentCode
                }
                if (that.TY) { //不是涂油
                    if (api.pageParam.ZS_ZhuSuReporID == 0) {
                        that.formData.reportID = "未上机"
                        that.clockInShow = true
                    } else {
                        that.formData.reportID = api.pageParam.ZS_ZhuSuReporID
                        that.formData.startTime = '后台已记录'
                        that.clockInShow = false
                    }
                } else {
                    that.clockInShow = false
                    if (api.pageParam.ZS_ZhuSuReporID == 0) {
                        that.formData.reportID = "未上机"
                    } else {
                        that.formData.reportID = api.pageParam.ZS_ZhuSuReporID
                        that.formData.startTime = '后台已记录'
                    }
                }
                that.getList()
                // var pin2 = localStorage.getItem('pin');
                // if (pin2) {
                //     that.fetchUserRole(pin2); // 重新查询权限
                //     // console.log('fffff')
                // }
                that.formData.empl = window.localStorage.getItem('loginName')

                if (api.pageParam.beforeMsg) {
                    that.formData.beforeBatch = api.pageParam.beforeMsg.Batch
                    that.formData.beforeEquipment = api.pageParam.beforeMsg.EquipmentCode
                }
                //  console.log('Equip' + api.pageParam.EquipmentCode)
                //  console.log('ZhuSuPlanDtlID' + that.tableData.ZhuSuPlanDtlID)

                // console.log('obj2', JSON.stringify(obj2))
                // console.log( 'obj2'+JSON.stringify(obj2))  

                //控制是否自动打印开启状态
                //  if (api.pageParam.roleName === '员工') {
                //      this.autoPrintEnabled = true;  // 员工默认开启
                //      this.startAutoPrintInterval();
                //  } else {
                //      this.autoPrintEnabled = false; // 其他角色默认关闭
                //      this.stopAutoPrintInterval();
                //  }
                //  that.getAutoPrintStatus()
                //  if(that.formData.empl === '严之鉴') {
                //         that.forceAutoPrint = false;
                //         that.showPrintControls = true;
                //         // return;
                //        }
                // if (api.pageParam.equipment.EquipmentID >= 3558 && api.pageParam.equipment.EquipmentID <= 3566) {
                //     APP.ajax('ZS_PDCB1', {

                //         // EquipmentID: api.pageParam.equipment.EquipmentID
                //     }, function (res) {
                //         if (res.ds1 && res.ds1[0]) {
                //             if (res.ds1[0].status == 500) {
                //                 // 超报情况，显示提示
                //                 api.alert({
                //                     title: '超报警告',
                //                     msg: res.ds1[0].message || '生产数量已超报，请及时处理！',
                //                     buttons: ['确定']
                //                 });

                //             }
                //         }
                //     })
                // }
                setTimeout(function () {
                    that.canEditQty = true;
                }, 10 * 1000);
                //
            },
            mounted() {
                var that = this
                window.addEventListener('keyup', that.inputFocus);
                var that = this;
                setInterval(function () {
                    var now = new Date();
                    var h = now.getHours();
                    var m = now.getMinutes();
                    var s = now.getSeconds();
                    // console.log('现在是：' + h+'时' + m+'分'+s+'秒')
                    // 早上 7:30
                    if (h === 7 && m === 30 && s === 0) {
                        that.clockOut();
                    }
                    // 晚上 19:30
                    if (h === 19 && m === 30 && s === 0) {
                        that.clockOut();
                    }
                }, 1000);
            },
            // beforeDestroy() {
            //     this.stopAutoPrintInterval()
            //     window.removeEventListener('keyup', this.inputFocus)
            // },
            methods: {
                recordTrainingTime(type) {
                    var that = this;
                    that.scanShow = true;
                    that.currentTrainingAction = type;
                    $('#autoInput').val('');
                    $("#autoInput").focus();

                    // 存储当前操作类型，用于扫描后的处理
                    // that.currentTrainingAction = type;
                },
                handleForceDisableAutoPrint() {
                    var that = this;
                    APP.ajax('ZS_UpdateAutoStatus', {
                        EquipmentID: api.pageParam.equipment.EquipmentID,
                        // status: 0  // 0表示关闭自动打印
                    }, function (res) {
                        if (res.ds && res.ds[0].status === 200) {
                            vm.$toast(res.ds[0].message);
                            // 刷新页面
                            // setTimeout(() => {
                            //     window.location.reload(); // 或使用 api.refresh()
                            // }, 1000);
                            that.getList()
                        } else {
                            vm.$toast('操作失败，请重试！');
                        }
                    });
                },
                getAutoPrintStatus() {
                    var that = this;
                    //  console.log('cccc'+window.localStorage.getItem('loginName'))
                    APP.ajax('ZS_GetAutoStatus', {
                        EquipmentID: api.pageParam.equipment.EquipmentID,
                        Name: window.localStorage.getItem('loginName')
                    }, function (res) {
                        if (res.ds && res.ds[0]) {
                            // console.log('jjjjjj'+JSON.stringify(res.ds))
                            // 接口返回1：强制自动打印模式
                            that.forceAutoPrint = res.ds[0].Status2 === 1;
                            that.showPrintControls = !that.forceAutoPrint;
                            that.realAutoPrintStatus = res.ds1[0].Status2;


                            if (that.forceAutoPrint) {
                                that.autoPrintEnabled = true;
                                that.startAutoPrintInterval();
                            }
                        }
                    });
                },
                validateBoxCode(code) {
                    // 定义箱码的正则表达式
                    const regex = /^(XM\|\d{8}\|\d{12})|(TY\d+)$/;

                    // 检查是否符合格式
                    if (!regex.test(code)) {
                        return false; // 不符合格式
                    }
                    return true; // 符合格式
                },
                handlerQualityReprint() {
                    this.qualityReprintShow = true;
                    this.qualityReprintCode = '';
                },

                // 确认品质补打
                confirmQualityReprint() {
                    var that = this
                    if (!this.qualityReprintCode) {
                        vm.$toast('请输入箱码！');
                        return;
                    }

                    if (!this.validateBoxCode(this.qualityReprintCode)) {
                        vm.$toast('箱码格式错误，请输入正确的箱码格式！');
                        return;
                    }
                    // 用 | 分割箱码（前端显示用，实际传参不需要）
                    // const formattedCode = this.qualityReprintCode.replace(/\|/g, '');

                    this.showPrintMsg = true;
                    this.printMsg = '标签补打中...';

                    // 调用品质补打接口（仿照原有补打逻辑）
                    APP.ajax('ZS_QualityReprint', {
                        FBoxCode: this.qualityReprintCode
                        // Operator: this.formData.empl
                    }, (res) => {
                        this.showPrintMsg = false;
                        this.qualityReprintShow = false;

                        if (res.ds[0]) {
                            // 补打逻辑（与原有补打相同）
                            console.log('res:' + JSON.stringify(res.ds[0]))
                            res.ds[0].FBoxCode = this.qualityReprintCode;
                            res.ds[0].ProductCode = res.ds[0].ProductCODE
                            res.ds[0].BaoZhangQTY = res.ds[0].ReporQTY
                            that.getPrint(res.ds[0], res.ds[0].FBoxCode, res.ds[0].FBoxNum)
                            // api.sendEvent({
                            //     name: 'printStatus',
                            //     extra: {
                            //         code: res.ds[0]
                            //     }
                            // });
                            vm.$toast('标签补打成功！');
                            this.qualityReprintCode = ''
                        } else {
                            vm.$toast('补打失败,未找到对应箱码！');
                        }
                    });
                },

                formatQualityCode() {
                    if (this.qualityReprintCode.length > 0) {
                        // 移除所有 | 后重新格式化
                        let code = this.qualityReprintCode.replace(/\|/g, '');
                        if (code.length > 4) {
                            this.qualityReprintCode =
                                code.substring(0, 2) + '|' +
                                code.substring(2, 10) + '|' +
                                code.substring(10);
                        }
                    }
                },

                startAutoPrintInterval() {
                    // 先清除已有定时器
                    this.stopAutoPrintInterval()
                    // 以1分钟(60000ms)间隔启动新定时器
                    this.intervalId = setInterval(this.autoPrintCheck, 10000)
                },

                stopAutoPrintInterval() {
                    if (this.intervalId) {
                        clearInterval(this.intervalId)
                        this.intervalId = null
                    }
                },
                // autoPrintCheck() {
                //     // 原有的自动打印逻辑
                //     // 用try-catch包裹防止未捕获错误
                //     try {
                //         // ...原有的自动打印代码
                //     } catch (error) {
                //         console.error('自动打印错误:', error)
                //     }
                // },

                autoPrintCheck() {
                    var that = this;
                    // if (!that.autoPrintEnabled) return;
                    // 1. 获取起始合模数（保持原有逻辑）
                    // console.log('自动打印检查触发，当前状态:', this.autoPrintEnabled);
                    if (!that.autoPrintEnabled || that.isBoxListOpen) {
                        return;

                    }
                    if (api.pageParam.equipment.EquipmentID < 3558 || api.pageParam.equipment.EquipmentID > 3566) {
                        //  console.log('111')
                        // setInterval(function () {

                        if (that.tableData.length === 1) {
                            //     var obj99= {
                            //         ZS_ZhuSuReporID: that.formData.reportID,
                            //     ZhuSuPlanID: that.formData.ZhuSuPlanID,
                            //     EquipmentID: api.pageParam.equipment.EquipmentID,
                            // }
                            var obj99 = {
                                ZhuSuPlanID: that.formData.ZhuSuPlanID,
                                ProductionNO: that.formData.ProductionNO,
                                EquipmentID: api.pageParam.equipment.EquipmentID
                            }
                            //      var obj = {
                            //     ZS_ZhuSuReporID: that.formData.reportID,
                            //     ZhuSuPlanID: that.formData.ZhuSuPlanID,
                            //     EquipmentID: api.pageParam.equipment.EquipmentID,
                            // }
                            // console.log('obj99'+JSON.stringify(obj99))
                            APP.ajax('ZsGetTotalQty', obj99, function (res9) {
                                if (res9.ds[0]) {
                                    // that.
                                    that.totalQtys = res9.ds[0].SumQty
                                    // console.log('res9' + JSON.stringify(res9))

                                    // console.log('当前订单明细已经累计生产了：' + that.totalQtys + '个')
                                }
                                that.continueAutoPrintCheck();
                            });

                        }
                        else {
                            var obj100 = {
                                ZhuSuPlanID: that.formData.ZhuSuPlanID,
                                ProductionNO: that.formData.ProductionNO,
                                EquipmentID: api.pageParam.equipment.EquipmentID
                            }
                            APP.ajax('ZsGetTotalQty', obj100, function (res10) {
                                if (res10.ds[0]) {
                                    that.totalQtys = res10.ds[0].SumQty / 2
                                    // console.log('res10' + JSON.stringify(res10))
                                    // console.log('当前订单明细已经累计生产了：' + that.totalQtys + '个')
                                }
                                that.continueAutoPrintCheck();
                            });
                        }


                        // console.log('这是累计数量11111111111111111:'+ that.ALBarCodeNum2)


                        // }, 30000); // 每10秒更新一次
                    }
                },


                // autoPrintCheck() {
                //     var that = this;
                //     // if (!that.autoPrintEnabled) return;
                //     // 1. 获取起始合模数（保持原有逻辑）
                //     // console.log('自动打印检查触发，当前状态:', this.autoPrintEnabled);
                //     if (!that.autoPrintEnabled)
                //         // console.log('自动打印已关闭，跳过检查');
                //         return;
                //     if (api.pageParam.equipment.EquipmentID < 3558 || api.pageParam.equipment.EquipmentID > 3566) {
                //         if (that.tableData.length === 1) {
                //             var obj99 = {
                //                 ZhuSuPlanID: that.formData.ZhuSuPlanID,
                //                 ProductionNO: that.formData.ProductionNO,
                //                 EquipmentID: api.pageParam.equipment.EquipmentID
                //             }


                //             var obj66 = {
                //                 Batch: that.formData.Batch,
                //                 EquipmentCode: api.pageParam.equipment.EquipmentID,
                //                 ProductID: that.tableData[0].ProductID
                //             }

                //             APP.ajax('ZS_GetRemainder', obj66, function (resRemainder) {
                //                 if (resRemainder.ds && resRemainder.ds[0]) {
                //                     var WeiShuQty = resRemainder.ds[0].RemainderQty || 0;
                //                     // 计算尾数对应的合模数
                //                     var weishuHM = WeiShuQty / that.XS;

                //                     APP.ajax('ZsGetTotalQty', obj99, function (res9) {
                //                         if (res9.ds[0]) {
                //                             that.totalQtys = res9.ds[0].SumQty;

                //                             // 获取当前QSHM
                //                             var obj55 = {
                //                                 ProductionNO: that.formData.ProductionNO,
                //                                 Batch: that.formData.Batch,
                //                                 EquipmentCode: api.pageParam.equipment.EquipmentCode,
                //                                 ProductID: that.tableData[0].ProductID,
                //                                 Type: 2, // Type=2表示查询
                //                                 QSHM: 0,
                //                                 Modify1: '123'
                //                             }

                //                             APP.ajax('ZS_SaveQSHM', obj55, function (resQSHM) {
                //                                 if (resQSHM.ds && resQSHM.ds[0]) {
                //                                     // 调整QSHM：减去尾数对应的合模数
                //                                     that.QSHM2 = resQSHM.ds[0].QSHM - weishuHM;
                //                                     that.correctedQuantitySS = 1;

                //                                     // 继续后续处理
                //                                     that.continueAutoPrintCheck();
                //                                 } else {
                //                                     that.continueAutoPrintCheck();
                //                                 }
                //                             });
                //                         } else {
                //                             that.continueAutoPrintCheck();
                //                         }
                //                     });
                //                 } else {
                //                     that.continueAutoPrintCheck();
                //                 }
                //             });
                //         } else {
                //             // 双穴产品的处理逻辑（类似单穴）
                //             var obj100 = {
                //                 ZhuSuPlanID: that.formData.ZhuSuPlanID,
                //                 ProductionNO: that.formData.ProductionNO,
                //                 EquipmentID: api.pageParam.equipment.EquipmentID
                //             }

                //             var obj66 = {
                //                 Batch: that.formData.Batch,
                //                 EquipmentCode: api.pageParam.equipment.EquipmentID,
                //                 ProductID: that.tableData[0].ProductID
                //             }

                //             APP.ajax('ZS_GetRemainder', obj66, function (resRemainder) {
                //                 if (resRemainder.ds && resRemainder.ds[0]) {
                //                     var WeiShuQty = resRemainder.ds[0].RemainderQty || 0;
                //                     var weishuHM = WeiShuQty / that.XS;

                //                     APP.ajax('ZsGetTotalQty', obj100, function (res10) {
                //                         if (res10.ds[0]) {
                //                             that.totalQtys = res10.ds[0].SumQty / 2;

                //                             var obj55 = {
                //                                 ProductionNO: that.formData.ProductionNO,
                //                                 Batch: that.formData.Batch,
                //                                 EquipmentCode: api.pageParam.equipment.EquipmentCode,
                //                                 ProductID: that.tableData[0].ProductID,
                //                                 Type: 2,
                //                                 QSHM: 0,
                //                                 Modify1: '123'
                //                             }

                //                             APP.ajax('ZS_SaveQSHM', obj55, function (resQSHM) {
                //                                 if (resQSHM.ds && resQSHM.ds[0]) {
                //                                     that.QSHM2 = resQSHM.ds[0].QSHM - weishuHM;
                //                                     that.correctedQuantitySS = 1;
                //                                     that.continueAutoPrintCheck();
                //                                 } else {
                //                                     that.continueAutoPrintCheck();
                //                                 }
                //                             });
                //                         } else {
                //                             that.continueAutoPrintCheck();
                //                         }
                //                     });
                //                 } else {
                //                     that.continueAutoPrintCheck();
                //                 }
                //             });
                //         }
                //     }
                // },
                continueAutoPrintCheck() {
                    var that = this;
                    var obj2 = {
                        EquipmentCode: api.pageParam.equipment.EquipmentCode,
                        ZhuSuPlanDtlID: that.tableData[0].ZhuSuPlanDtlID
                    };
                    var obj3 = {
                        EquipmentCode: api.pageParam.equipment.EquipmentCode,
                        ProductID: that.tableData[0].ProductID
                    };
                    var obj4 = {
                        ZhuSuPlanID: that.formData.ZhuSuPlanID,
                        Batch: that.formData.Batch,
                        ZS_ZhuSuReporID: that.formData.reportID || 0,
                        ZhuSuPlanDtlID: that.tableData[0].ZhuSuPlanDtlID,
                        EquipmentID: api.pageParam.equipment.EquipmentID
                    }
                    var obj55 = {
                        ProductionNO: that.formData.ProductionNO,
                        Batch: that.formData.Batch,
                        EquipmentCode: api.pageParam.equipment.EquipmentCode,
                        ProductID: that.tableData[0].ProductID,
                        Type: 2, // Type=2表示查询
                        QSHM: 0,
                        Modify1: '123'

                    }
                    var obj66 = {
                        Batch: that.formData.Batch,
                        EquipmentCode: api.pageParam.equipment.EquipmentID,
                        ProductID: that.tableData[0].ProductID

                    }
                    //    console.log('这是请求体obj55'+ JSON.stringify(obj55))
                    APP.ajax('ZS_SaveQSHM', obj55, function (res) {
                        if (res.ds && res.ds[0]) {
                            that.QSHM2 = res.ds[0].QSHM;
                            that.correctedQuantitySS = 1
                            //  console.log('获取到保存的QSHM2值:', that.QSHM2);
                        } else {
                            //  console.log('未获取到保存的QSHM2值，使用默认值');
                            that.correctedQuantitySS = 0
                            // that.QSHM2 = that.QSHM; // 如果没有保存的值，使用原始QSHM
                        }
                        // console.log('obj4:' + JSON.stringify(obj4))
                        APP.ajax('ZS_FoxboxList_TY1', obj4, function (res8) {
                            // console.log('ggggg')
                            if (res8) {
                                // console.log('res8' + JSON.stringify(res8))
                                that.ALBarCodeNum = Math.max(0, res8.ds && res8.ds[0] ? res8.ds[0].YBGXS : 0);
                                that.ALBarCodeNum2 = Math.max(0, res8.ds1 && res8.ds1[0] ? res8.ds1[0].SUMReporQTY : 0);
                                that.BadProductsTotal = Math.max(0, res8.ds2 && res8.ds2[0] ? res8.ds2[0].BadQTY : 0);
                                // console.log('当前批次总共有不良：' + that.BadProductsTotal + '个')
                                APP.ajax('ZS_PrintStartNum2', obj2, function (res) {
                                    if (res.ds[0].value && res.ds[0].times && res.ds[0].UpTime) {
                                        that.updateQSHM(res.ds[0].value); // 更新起始合模数
                                        // console.log('这是起始合模:' + that.QSHM);
                                        // console.log('这是上机起始时间：' + res.ds[0].times)
                                        // console.log('这是合模起始时间：' + res.ds[0].UpTime)
                                        // var timesStr = res.ds[0].times; // "2025-04-14 07:40:08"
                                        // var upTimeStr = res.ds[0].UpTime; // "2025-04-14 07:44:23"

                                        // var times = new Date(timesStr.replace(/-/g, '/'));
                                        // var upTime = new Date(upTimeStr.replace(/-/g, '/'));


                                        // var timeDiffMinutes = (upTime - times) / (1000 * 60);
                                        // if (timeDiffMinutes > 30) {
                                        //     api.toast({
                                        //         msg: '请重新上下机！',
                                        //         duration: 3000,
                                        //         location: 'middle'
                                        //     })
                                        //     return;
                                        // }

                                        if (that.QSHM > 0 && that.QSHM !== null) {
                                            APP.ajax('ZS_Numdetail', obj3, function (res0) {
                                                if (res0.ds[0]) {
                                                    var newSSHM = res0.ds[0].value; // 获取新的实时合模数
                                                    that.updateSSHM(newSSHM); // 更新实时合模数
                                                    that.XS = res0.ds1[0].XS;
                                                    // console.log('这是实时合模:' + that.SSHM);
                                                    // console.log('这是模穴数量:' + that.XS);

                                                    //  计算当前生产数量
                                                    if (isNaN(that.SSHM) || isNaN(that.QSHM2) || isNaN(that.XS) ||
                                                        !isFinite(that.SSHM) || !isFinite(that.QSHM2) || !isFinite(that.XS)) {
                                                        // console.error('无效的数值:', {
                                                        //     SSHM: that.SSHM,
                                                        //     QSHM2: that.QSHM2,
                                                        //     XS: that.XS
                                                        // });

                                                        console.log(9)
                                                        return;

                                                    }
                                                    let calculatedQty;
                                                    // if (that.correctedQuantitySS <= 0) {
                                                    //     that.QSHM2 = that.QSHM; // 
                                                    // }
                                                    if (that.correctedQuantitySS > 0) {
                                                        calculatedQty = (Number(that.SSHM) - Number(that.QSHM2)) * Number(that.XS);
                                                        // console.log('计算值：'+calculatedQty ,'起始合模：'+that.QSHM2)
                                                        if (that.correctedQuantitySS > calculatedQty) {
                                                            that.QuantitySS = that.correctedQuantitySS;
                                                            // console.log(111)
                                                        } else {
                                                            that.QuantitySS = Math.max(0, calculatedQty); // 确保不小于0
                                                            // console.log(222+that.QuantitySS)
                                                        }
                                                    } else {
                                                        calculatedQty = (Number(that.SSHM) - Number(that.QSHM)) * Number(that.XS);
                                                        that.QuantitySS = Math.max(0, calculatedQty); // 确保不小于0
                                                        // console.log(333)
                                                    }
                                                    if (isNaN(that.QuantitySS) || !isFinite(that.QuantitySS)) {
                                                        //   console.error('计算出的QuantitySS无效:', that.QuantitySS);
                                                        return;
                                                        console.log(8)
                                                    }
                                                    // console.log('不良前累计：' + that.QuantitySS)
                                                    // that.QuantitySS = that.QuantitySS - that.BadProductsTotal;
                                                    that.QuantitySS = Math.max(0, that.QuantitySS - that.BadProductsTotal);
                                                    that.QuantityAlPrint = that.QuantitySS % Number(that.tableData[0].BaoZhangQTY);
                                                    var NotalreadyPrintNums = that.QuantitySS - Number(that.ALBarCodeNum2)
                                                    // var lastPrintedQuantity = that.lastPrintedQuantity || 0; 

                                                    // console.log('当前已经生产了：' + that.QuantitySS + '个' + that.tableData[0].ProductName);

                                                    // console.log('当前已经包装了：' + that.ALBarCodeNum2 + '个' + that.tableData[0].ProductName);

                                                    // console.log('待打印数量：' + NotalreadyPrintNums)
                                                    // 判断是否需要打印
                                                    if ((that.SSHM !== null || that.SSHM !== 0) && (that.QSHM !== null || that.QSHM !== 0) && (that.XS !== null || that.XS !== 0)) {


                                                        if (that.tableData.length === 1) {
                                                            var baoZhangQTY = Number(that.tableData[0].BaoZhangQTY);
                                                            // var PlanQianQTY = Number(that.tableData[0].PlanQianQTY);
                                                            var PlanQTY = Number(that.tableData[0].PlanQTY1);
                                                            that.fnumber1 = PlanQTY - Number(that.totalQtys)
                                                            // console.log('订单数为：'+PlanQTY )
                                                            // 如果订单欠数小于包装数量，且订单欠数大于0，临时修改包装数量为订单欠数
                                                            // console.log('当前未做：'+that.fnumber1+'件')
                                                            if (that.fnumber1 <= 0) {
                                                                // console.log("当前订单已经做完，跳过打印任务");
                                                                return; // 如果自动打印未开启，则跳过
                                                            }
                                                            // if (that.fnumber1 < baoZhangQTY && that.fnumber1 > 0) {
                                                            //     baoZhangQTY = that.fnumber1;
                                                            //     that.tableData[0].BaoZhangQTY = baoZhangQTY
                                                            //     // console.log('订单欠数不足，临时修改包装数量为：' + baoZhangQTY);
                                                            // }

                                                            // 计算待打印数量
                                                            var NotalreadyPrintNums = that.QuantitySS - Number(that.ALBarCodeNum2);
                                                            if (!that.autoPrintEnabled) {
                                                                // console.log("自动打印已关闭，跳过打印任务");
                                                                return; // 如果自动打印未开启，则跳过
                                                            } else {
                                                                // 判断是否需要打印
                                                                if (NotalreadyPrintNums >= baoZhangQTY && that.fnumber1 > 0) {

                                                                    that.handlePrint()
                                                                }
                                                            }
                                                        } else if (that.tableData.length === 2) {
                                                            var baoZhangQTY = Number(that.tableData[0].BaoZhangQTY); // 左边包装数
                                                            var pairCount = Math.floor(NotalreadyPrintNums / baoZhangQTY);

                                                            if (pairCount > 0 && !that.pairPrinting) {
                                                                that.pairPrinting = true; // 锁住下一套
                                                                that.pairSide = 1;  // 必须从左边开始
                                                                that.printPair();         // 发起成对打印
                                                            }
                                                            return; // 不再走旧逻辑
                                                        }
                                                    } else {
                                                        return
                                                        console.log(7)
                                                        // that.calculateQuantitySS()

                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                            // }
                            else {
                                // console.log('无返回！！！')
                                return;
                            }
                        });
                    });
                },
                toggleAutoPrint() {
                    if (this.forceAutoPrint) {
                        vm.$toast('当前设备强制自动打印模式，不可关闭');
                        return;
                    }

                    this.autoPrintEnabled = !this.autoPrintEnabled; // 切换状态
                    if (this.autoPrintEnabled) {
                        // console.log("自动打印已开启");

                        // vm.$toast('自动打印已开启！');

                        api.toast({
                            msg: '自动打印已开启！',
                            duration: 3000,
                            location: 'middle'
                        })
                        this.startAutoPrintInterval()
                    } else {
                        // console.log("自动打印已关闭");
                        api.toast({
                            msg: '自动打印已关闭！',
                            duration: 3000,
                            location: 'middle'
                        })
                        this.stopAutoPrintInterval()
                    }
                },

                printPair: function () {
                    var that = this;
                    if (that.pairSide === 1) {
                        that.printCode1('序号1');   // 先打左
                    } else if (that.pairSide === 2) {
                        that.printCode2('序号2');   // 再打右
                    }
                },
                // printCodeWithDelay(btn, table, delay = 3000) {
                //     setTimeout(() => {
                //        this.printCode1(btn, table);
                //         }, delay);
                //    },handlePrint() {
                //       this.printCodeWithDelay('序号1', this.tableData[0], 0); // 立即打印第一个
                //      this.printCodeWithDelay('序号2', this.tableData[1], 3000); // 3秒后打印第二个
                //      },
                printCodeWithDelay(btn) {
                    // setTimeout(() => {
                    if (btn === '序号1') {
                        this.printCode1(btn);
                    } else if (btn === '序号2') {
                        this.printCode2(btn);
                    }
                    // }, delay);
                },
                handlePrint() {
                    this.printCodeWithDelay('序号1');
                },

                handlePrint2() {
                    var that = this;


                    that.printQueue = [];


                    that.printQueue.push({ type: 'print1', btn: '序号1' });
                    that.printQueue.push({ type: 'print2', btn: '序号2' });


                    if (that.printQueue.length > 0) {
                        var firstPrint = that.printQueue.shift();
                        if (firstPrint.type === 'print1') {
                            that.printCode1(firstPrint.btn);
                        }
                    }
                },
                openEditQuantitySSPopup() {
                    var that = this;
                    if (!that.canEditQty) {
                        var left = 10 - Math.floor((Date.now() - that.enterTime) / 1000);
                        vm.$toast('请稍后再试（' + (left > 0 ? left : 1) + ' 秒后可修改）');
                        return;
                    }

                    that.stopAutoPrintInterval();
                    that.showEditQuantitySSPopup = true;
                    that.editQuantitySS = that.QuantitySS;
                },

                confirmEditQuantitySS() {
                    var that = this;
                    if (that.editQuantitySS === null || isNaN(that.editQuantitySS) || that.editQuantitySS < 0) {
                        vm.$toast('请输入有效的数值！');
                        return;
                    }

                    vm.$dialog.confirm({
                        title: '确认修改',
                        message: `确定要将累计生产数量从 ${that.QuantitySS} 修改为 ${that.editQuantitySS} 吗？`,
                        confirmButtonText: '确认修改',
                        cancelButtonText: '再想想'
                    }).then(() => {

                        that.correctedQuantitySS = Number(that.editQuantitySS);
                        that.QuantitySS = that.correctedQuantitySS;
                        that.QSHM2 = that.SSHM - Math.floor(that.correctedQuantitySS / that.XS);

                        var obj = {
                            ProductionNO: that.formData.ProductionNO,
                            Batch: that.formData.Batch,
                            EquipmentCode: that.formData.EquipmentCode,
                            Modify1: window.localStorage.getItem('loginName'),
                            QSHM: that.QSHM2,
                            ProductID: that.tableData[0].ProductID,
                            Type: 1
                        };

                        APP.ajax('ZS_SaveQSHM', obj, function (res) {
                            // if (res.ds) {
                            vm.$toast('修改成功！');
                            that.showEditQuantitySSPopup = false;

                            // 如果之前自动打印是开启的，重新开启
                            if (that.autoPrintEnabled) {
                                that.startAutoPrintInterval();
                            }
                            // } else {
                            //     vm.$toast('修改失败，请重试！');
                            // }
                        });
                    }).catch(() => {
                        // 用户取消修改
                        that.showEditQuantitySSPopup = false;
                        if (that.autoPrintEnabled) {
                            that.startAutoPrintInterval(); // 恢复自动打印
                        }
                    });
                },
                updateSSHM(value) {
                    var that = this
                    that.SSHM = value; // 更新SSHM的值
                },
                updateQSHM(value) {
                    var that = this
                    that.QSHM = value; // 更新QSHM的值
                },
                openScan() {
                    var that = this
                    that.inputCode = ''
                    that.scanShow = true
                    that.$refs.input.setAttribute('readonly', 'readonly');

                    scanS60A.registerReceiver(function (ret, err) {
                        // alert('ret' + JSON.stringify(ret))
                        if (ret.barcode) {
                            api.sendEvent({
                                name: 'newTYcode',
                                extra: {
                                    TYcode: ret.barcode,
                                }
                            })

                            that.pageBack()
                        } else {
                            vm.$toast('箱码识别失败，请重试！');
                        }
                    })
                },
                handlerPXName() {
                    var that = this
                    that.scanShow = true
                    $('#autoInput').val('');
                    $("#autoInput").focus();
                },
                //  inputFocus(e) {
                //      var that = this
                //      if (e.keyCode == 13) {
                //          let InputData = $("#autoInput").val().replace(" ", "").replace(" ", "");
                //          // 进行扫描数据的处理
                //          that.$refs.input.setAttribute('readonly', 'readonly');
                //          console.log('InputData', JSON.stringify(InputData))
                //          if (InputData) {
                //              vm.$toast(InputData)
                //              APP.ajax('ZS_CardLogin', { P_Card: InputData }, function (res) {
                //                  if (res.ds[0].status == 200) {
                //                      that.trainData.PXName = res.ds[0].Name
                //                      that.scanShow = false
                //                  } else {
                //                      vm.$toast('人员识别失败，请重试！');
                //                  }
                //                  that.inputCode = ''
                //              })
                //          } else {
                //              api.toast({
                //                  msg: '人员识别失败，请重试！'
                //              })
                //          }
                //          that.$refs.input.removeAttribute('readonly');
                //          $('#autoInput').val('');
                //          $("#autoInput").focus();
                //      }
                //  },
                // inputFocus(e) {
                //     var that = this;
                //     if (e.keyCode == 13) {
                //         let InputData = $("#autoInput").val().replace(" ", "").replace(" ", "");
                //         that.$refs.input.setAttribute('readonly', 'readonly');
                //         console.log('InputData', JSON.stringify(InputData));

                //         if (InputData) {
                //             vm.$toast(InputData);
                //             APP.ajax('ZS_CardLogin', { P_Card: InputData }, function (res) {
                //                 if (res.ds[0].status == 200) {
                //                     // 如果是培训时间记录操作
                //                     if (that.currentTrainingAction) {
                //                         var currentTime = that.getFormatTime(new Date());
                //                         if (that.currentTrainingAction === 'start') {
                //                             that.trainData.startTime = currentTime;
                //                             vm.$toast('培训开始时间已记录');
                //                         } else if (that.currentTrainingAction === 'end') {
                //                             that.trainData.endTime = currentTime;
                //                             vm.$toast('培训结束时间已记录');
                //                         }
                //                         that.currentTrainingAction = null; // 重置操作类型
                //                     } else {
                //                         // 原有的培训人选择逻辑
                //                         that.trainData.PXName = res.ds[0].Name;
                //                     }
                //                     that.scanShow = false;
                //                 } else {
                //                     vm.$toast('人员识别失败，请重试！');
                //                 }
                //                 that.inputCode = '';
                //             });
                //         } else {
                //             api.toast({
                //                 msg: '人员识别失败，请重试！'
                //             });
                //         }
                //         that.$refs.input.removeAttribute('readonly');
                //         $('#autoInput').val('');
                //         $("#autoInput").focus();
                //     }
                // },

                inputFocus(e) {
                    var that = this;
                    if (e.keyCode == 13) {
                        let InputData = $("#autoInput").val().replace(/\s+/g, '');
                        that.$refs.input.setAttribute('readonly', 'readonly');

                        if (!InputData) {
                            api.toast({ msg: '刷卡数据为空，请重试！' });
                            that.$refs.input.removeAttribute('readonly');
                            $('#autoInput').val('');
                            $("#autoInput").focus();
                            return;
                        }

                        APP.ajax('ZS_CardLogin', { P_Card: InputData }, function (res) {
                            if (res.ds[0].status == 200) {
                                var name = res.ds[0].Name;
                                var time = that.getFormatTime(new Date());

                                if (that.currentTrainingAction === 'start') {
                                    // ✅ 一次刷卡：同时记录培训人和开始时间
                                    that.trainData.PXName = name;
                                    that.trainData.startTime = time;
                                    vm.$toast('培训人及开始时间已记录');

                                } else if (that.currentTrainingAction === 'end') {
                                    that.trainData.endTime = time;
                                    vm.$toast('培训结束时间已记录');
                                }

                                that.scanShow = false;
                            } else {
                                vm.$toast('人员识别失败，请重试！');
                            }

                            that.inputCode = '';
                            that.$refs.input.removeAttribute('readonly');
                            $('#autoInput').val('');
                            $("#autoInput").focus();
                        });
                    }
                },


                // handlerTrain() { //岗前培训弹窗确认按钮
                //     var that = this
                //     // console.log('tableData', JSON.stringify(that.tableData))
                //     if (!that.trainData.PXName) {
                //         vm.$toast('请输入培训人！');
                //         return false
                //     }
                //     var obj = {
                //         ProductID: that.tableData[0].ProductID,
                //         ProductID1: that.tableData[1] ? that.tableData[1].ProductID : 0,
                //         CZName: window.localStorage.getItem('loginName'),
                //         ProductionNo: that.formData.ProductionNO,
                //         ZhuSuPlanID: that.formData.ZhuSuPlanID,
                //         PXName: that.trainData.PXName,
                //         FRemarks: that.trainData.FRemarks
                //     }
                //     // console.log('obj', JSON.stringify(obj))
                //     APP.ajax('getPreJob', obj, function (res) {
                //         // console.log('res', JSON.stringify(res))
                //         if (res.ds[0].status == 500) {
                //             api.toast({
                //                 msg: res.ds[0].msg
                //             })
                //             return false
                //         } else {
                //             api.toast({
                //                 msg: '已培训！'
                //             })
                //             that.trainShow = false
                //             that.clockIn()
                //         }
                //     })
                // },
                handlerTrain() { //岗前培训弹窗确认按钮
                    var that = this;
                    if (!that.trainData.PXName) {
                        vm.$toast('请输入培训人！');
                        return false;
                    }
                    if (!that.trainData.startTime) {
                        vm.$toast('请输入培训开始时间！');
                        return false;
                    }
                    if (!that.trainData.endTime) {
                        vm.$toast('请输入培训结束时间！');
                        return false;
                    }

                    var obj = {
                        ProductID: that.tableData[0].ProductID,
                        ProductID1: that.tableData[1] ? that.tableData[1].ProductID : 0,
                        CZName: window.localStorage.getItem('loginName'),
                        ProductionNo: that.formData.ProductionNO,
                        ZhuSuPlanID: that.formData.ZhuSuPlanID,
                        PXName: that.trainData.PXName,
                        FRemarks: that.trainData.FRemarks,
                        StartTime: that.trainData.startTime, // 新增：培训开始时间
                        EndTime: that.trainData.endTime      // 新增：培训结束时间
                    };

                    console.log('培训参数', JSON.stringify(obj));

                    // 使用新的接口传入培训时间
                    APP.ajax('getPreJob1', obj, function (res) {
                        console.log('培训结果', JSON.stringify(res));
                        if (res.ds[0].status == 500) {
                            api.toast({
                                msg: res.ds[0].msg
                            });
                            return false;
                        } else {
                            api.toast({
                                msg: '培训完成！'
                            });
                            that.trainShow = false;
                            that.clockIn();
                        }
                    });
                },

                openBaseScreen: function (str) {
                    var that = this;
                    var obj;
                    if (str == '机台') {
                        obj = {
                            allowClear: false,
                            showSearch: true,
                            searchKey: '',
                            serverSearch: false,
                            searchBy: ['EquipmentName'],
                            isPaging: false,
                            type: str,
                            cmd: 'getZSEquipment',
                            param: {
                            }
                        }
                    }

                    api.openWin({
                        name: 'baseScreen',
                        url: 'common/baseScreen.html',
                        reload: true,
                        slidBackEnabled: false,
                        pageParam: obj
                    })
                },
                cancelPrint() {
                    var that = this
                    that.showPrintMsg = false
                    that.ifConfirm1 = false
                    that.ifConfirm2 = false
                },
                printCode1(btn) {
                    var that = this
                    if (that.currentPrinting) {
                        that.printQueue.push({ type: 'print1', btn: btn });
                        vm.$toast('已加入打印队列');
                        return;
                    }
                    that.currentPrinting = 'print1';
                    that.currentBtn = btn
                    that.showPrintMsg = true
                    that.ifConfirm1 = false
                    that.printMsg = '序号1箱码生成中...'
                    that.getOver(that.tableData[0], 0)
                },
                printCode2(btn) {
                    var that = this
                    if (that.currentPrinting) {
                        that.printQueue.push({ type: 'print2', btn: btn });
                        vm.$toast('已加入打印队列');
                        return;
                    }

                    that.currentPrinting = 'print2';
                    that.currentBtn = btn
                    that.showPrintMsg = true
                    that.ifConfirm2 = false
                    that.printMsg = '序号2箱码生成中...'
                    that.getOver(that.tableData[1], 1)
                },
                historyBack() {
                    var that = this
                    api.closeFrame()
                },
                getList() {
                    var that = this
                    var obj = {
                        EquipmentID: api.pageParam.equipment.EquipmentID,
                        ZhuSuPlanID: api.pageParam.ZhuSuPlanID,
                        ZS_ZhuSuReporID: that.formData.reportID == '未上机' ? 0 : that.formData.reportID
                    }
                    console.log('obj', JSON.stringify(obj))
                    APP.ajax('getZSPlanList', obj, function (res) {
                        console.log('res', JSON.stringify(res))
                        that.formData.ProductionNO = res.ds[0].ProductionNO
                        that.formData.WhetherStarteEquipment = res.ds[0].WhetherStarteEquipment
                        that.formData.ZhuSuPlanNO = res.ds[0].BillNO
                        that.formData.HourModulus = res.ds[0].HourModulus
                        that.formData.PlanFinsh = res.ds[0].PlanFinsh ? res.ds[0].PlanFinsh.replace('T', ' ').split('.')[0] : ''
                        that.formData.Batch = res.ds[0].Batch1 || api.pageParam.currentBatch
                        var table = []
                        res.ds.map((item, index) => {
                            table.push(
                                {
                                    number: index + 1,
                                    MONO: item.MONO,
                                    ProductCode: item.ProductCode,
                                    ProductName: item.ProductName,
                                    ProductID: item.ProductID,
                                    ProductSpec: item.ProductSpec == null ? '' : item.ProductSpec,
                                    BaoZhangQTY: item.BaoZhangQTY,
                                    PlanQTY1: item.PlanQTY1,
                                    PlanQianQTY: item.PlanQianQTY,
                                    ZhuSuPlanDtlID: item.ZhuSuPlanDtlID,
                                    HourModulus: item.HourModulus
                                }
                            )
                        })
                        that.tableData = table

                        if (that.TY && that.formData.reportID == '未上机') {  //普通注塑机未上机的
                            var obj1 = {
                                ProductID: that.tableData[0].ProductID,
                                ProductID1: that.tableData[1] ? that.tableData[1].ProductID : 0,
                                EquipmentID: api.pageParam.equipment.EquipmentID,
                                CZName: window.localStorage.getItem('loginName'),
                            }
                            console.log('obj1', JSON.stringify(obj1))
                            APP.ajax('isPreJobT', obj1, function (res) { //判断操作工有无培训过
                                console.log('res', JSON.stringify(res))
                                if (res.ds[0].Column1) { //1:操作工没培训过+提示弹框的
                                    that.trainShow = true
                                    that.stopAutoPrintInterval()
                                } else { //1:操作工培训过+直接上机
                                    that.clockIn()
                                    that.startAutoPrintInterval()
                                }
                            })
                        } else if (!that.TY) {  //涂油机台自动上机
                            that.TYclock()
                        }
                        console.log('that.tableData', JSON.stringify(that.tableData))
                        that.showBtn2 = !that.clockInShow && that.tableData.length == 2 ? true : false
                    })
                    that.correctedQuantitySS = 0;
                    that.getAutoPrintStatus();
                    //  var storedQty = localStorage.getItem(`correctedQty_${this.formData.reportID}`);
                    //  if(storedQty) {
                    //     that.correctedQuantitySS = Number(storedQty);
                    //     that.QSHM2 = Number(localStorage.getItem(`QSHM2_${this.formData.reportID}`));
                    //    }
                },
                editBaoZhang(edit, index) {
                    var that = this
                    that.currentIndex = index
                    api.frameHeight = that.initialHeight
                    that.editBaoZhangQTY = ''
                    that.showEditBaoZhang = true
                    that.currerntEdit = {}
                    if (edit) {
                        that.currerntEdit = edit
                    }
                },
                confirmBaoZhangQTY() {
                    var that = this
                    that.showEditBaoZhang = false
                    if (that.currerntEdit.number) {
                        if (that.editBaoZhangQTY <= that.currerntEdit.BaoZhangQTY) {
                            that.tableData[that.currentIndex].BaoZhangQTY = that.editBaoZhangQTY
                        } else {
                            vm.$dialog.confirm({
                                message: '您修改的包装数量超出限制，若要修改请找班组长！',
                            })
                                .then(() => {
                                })
                                .catch(() => {
                                });
                        }
                    } else {
                        that.tableData.map((item) => {
                            item.BaoZhangQTY = that.editBaoZhangQTY
                            var obj = {
                                ProductSpec: item.ProductSpec,
                                ProductID: item.ProductID,
                                ProductCode: item.ProductCode,
                                ChangeNum: item.BaoZhangQTY,
                                ProductName: item.ProductName,
                                Name: window.localStorage.getItem('loginName'),
                            }
                            APP.ajax('ZS_ChangeBoxNum', obj, function (res) {
                            })
                        })
                        vm.$toast('包装数量修改成功！')
                    }
                },
                clockOut() {
                    var that = this
                    var obj = {
                        ZS_ZhuSuReporID: that.formData.reportID,
                        ZhuSuPlanID: api.pageParam.ZhuSuPlanID
                    }
                    APP.ajax('ZS_DownEquipment', obj, function (res) {
                        if (res.ds[0].status == 200) {
                            vm.$toast(res.ds[0].msg)
                            that.formData.endTime = that.getFormatTime(new Date())
                            // if (api.pageParam.equipment.EquipmentID >= 3558 && api.pageParam.equipment.EquipmentID <= 3566) {
                            //     var url1 = 'http://' + APP.serverIP() + '/Frame/ST1_LLS/ZSRFIDHandler.aspx?cmd=submitData';
                            //     var url2 = 'http://' + APP.serverIP() + '/Frame/ST1_LLS/ZSRFIDHandler.aspx?cmd=pushBoxCode';

                            //     // 调用第一个接口
                            //     $.ajax({
                            //         url: url1,
                            //         type: 'GET',
                            //         contentType: 'application/json',
                            //         data: null,
                            //         success: function (data) {
                            //             console.log('成功:', data);


                            //         },
                            //         error: function (xhr, status, error) {
                            //             console.error('失败:', error);
                            //         }
                            //     });
                            // }

                            api.sendEvent({
                                name: 'refreshChoosePlan'
                            })
                            api.sendEvent({
                                name: 'refreshBrowser',
                                extra: {
                                    choosePlan: false
                                }
                            })
                            setTimeout(() => {
                                that.pageBack()
                            }, 3000)
                        } else {
                            that.$dialog.confirm({
                                title: '提示',
                                message: '下机失败，请重试！',
                                confirmButtonText: '确认下机'
                            })
                                .then(() => {
                                    that.clockOut()
                                })
                                .catch(() => {
                                });
                        }
                    })
                },
                // clockOut() {
                //     var that = this;

                //     // 只有当累计生产数量>0时才计算和保存尾数
                //     if (that.QuantitySS > 0) {
                //         // 计算尾数
                //         const WeiShuQty = that.QuantitySS % that.tableData[0].BaoZhangQTY;

                //         // 保存尾数数据
                //         APP.ajax('ZS_SaveRemainder', {
                //             EquipmentID: api.pageParam.equipment.EquipmentID,
                //             ProductID: that.tableData[0].ProductID,
                //             RemainderQty: WeiShuQty,  // 
                //             Batch: that.formData.Batch,
                //             Operator: that.formData.empl,
                //             ProductionNO: that.formData.ProductionNO,
                //             ZS_ZhuSuReporID: that.formData.ZS_ZhuSuReporID
                //         }, function (res) {

                //             if (res.ds[0].Column1) {
                //                 // 尾数保存成功后执行下机操作
                //                 var obj = {
                //                     ZS_ZhuSuReporID: that.formData.reportID,
                //                     ZhuSuPlanID: api.pageParam.ZhuSuPlanID
                //                 };
                //                 APP.ajax('ZS_DownEquipment', obj, function (res2) {
                //                     if (res2.ds[0].status == 200) {
                //                         vm.$toast(res2.ds[0].msg);
                //                         that.formData.endTime = that.getFormatTime(new Date());

                //                         api.sendEvent({
                //                             name: 'refreshChoosePlan'
                //                         });
                //                         api.sendEvent({
                //                             name: 'refreshBrowser',
                //                             extra: {
                //                                 choosePlan: false
                //                             }
                //                         });

                //                         setTimeout(() => {
                //                             that.pageBack();
                //                         }, 3000);
                //                     } else {
                //                         that.$dialog.confirm({
                //                             title: '提示',
                //                             message: '下机失败，请重试！',
                //                             confirmButtonText: '确认下机'
                //                         })
                //                             .then(() => {
                //                                 that.clockOut();
                //                             })
                //                             .catch(() => { });
                //                     }
                //                 });
                //             }
                //         });
                //     } else {
                //         var obj = {
                //             ZS_ZhuSuReporID: that.formData.reportID,
                //             ZhuSuPlanID: api.pageParam.ZhuSuPlanID
                //         };
                //         APP.ajax('ZS_DownEquipment', obj, function (res2) {
                //             if (res2.ds[0].status == 200) {
                //                 vm.$toast(res2.ds[0].msg);
                //                 that.formData.endTime = that.getFormatTime(new Date());

                //                 api.sendEvent({
                //                     name: 'refreshChoosePlan'
                //                 });
                //                 api.sendEvent({
                //                     name: 'refreshBrowser',
                //                     extra: {
                //                         choosePlan: false
                //                     }
                //                 });

                //                 setTimeout(() => {
                //                     that.pageBack();
                //                 }, 3000);
                //             } else {
                //                 that.$dialog.confirm({
                //                     title: '提示',
                //                     message: '下机失败，请重试！',
                //                     confirmButtonText: '确认下机'
                //                 })
                //                     .then(() => {
                //                         that.clockOut();
                //                     })
                //                     .catch(() => { });
                //             }
                //         });
                //     }
                // },
                TYclock() { //开始涂油
                    var that = this
                    var obj = {
                        ZhuSuPlanID: api.pageParam.ZhuSuPlanID, //注塑计划ID
                        MouldID: 0,//模具ID
                        EquipmentID: api.pageParam.equipment.EquipmentID,//机台ID
                        ZhuSuPlanNO: that.formData.BillNO == null ? 1 : '',//注塑计划单号
                        ProductionNO: that.formData.ProductionNO,//生产单号
                        WhiteORNight: api.pageParam.classOption.indexOf('白班') == -1 ? 0 : 1,//白夜班
                        Batch: that.formData.Batch, //批次号
                        pin: window.localStorage.getItem('pin'), //员工ID
                        empolorName: window.localStorage.getItem('loginName'), //员工姓名
                        CardID: window.localStorage.getItem('card_no'),//员工卡号
                        Productid: that.tableData[0].ProductID || 0
                    }
                    console.log('obj', JSON.stringify(obj))
                    APP.ajax('ZS_ChangeTYBG', obj, function (res) {
                        console.log('res', JSON.stringify(res))
                        if (res.ds[0].ZS_ZhuSuReporID) {
                            that.formData.reportID = res.ds[0].ZS_ZhuSuReporID
                            vm.$toast('开始涂油！')

                            api.sendEvent({
                                name: 'refreshChoosePlan'
                            })

                            // setTimeout(() => {
                            //     that.printCode1('序号1')
                            // }, 2000)
                        } else {
                            vm.$toast('开始涂油失败，请重试！')
                        }
                    })
                },

                clockIn() { //普通注塑机台上机打卡
                    var that = this
                    if (!that.formData.Batch) {
                        vm.$toast('批次号为空，请返回重新进入！')
                        return false
                    }

                    var obj = {
                        ZhuSuPlanID: api.pageParam.ZhuSuPlanID, //注塑计划ID
                        MouldID: 0,//模具ID
                        EquipmentID: api.pageParam.equipment.EquipmentID,//机台ID
                        ZhuSuPlanNO: that.formData.BillNO == null ? 1 : '',//注塑计划单号
                        ProductionNO: that.formData.ProductionNO,//生产单号
                        WhiteORNight: api.pageParam.classOption.indexOf('白班') == -1 ? 0 : 1,//白夜班
                        Batch: that.formData.Batch, //批次号
                        pin: window.localStorage.getItem('pin'), //员工ID
                        empolorName: window.localStorage.getItem('loginName'), //员工姓名
                        CardID: window.localStorage.getItem('card_no'),//员工卡号
                    }
                    //  var equipmentID = api.pageParam.equipment.EquipmentID
                    APP.ajax('ZS_ChangeEquipment', obj, function (res) {
                        if (res.ds[0].status == 200) {
                            if (that.formData.reportID == '未上机') {
                                that.formData.reportID = res.ds[0].ZS_ZhuSuReporID
                                that.formData.startTime = that.getFormatTime(new Date())
                                vm.$toast('上机打卡成功！')
                                that.clockInShow = false
                                that.showBtn2 = !that.clockInShow && that.tableData.length == 2 ? true : false
                                // if (api.pageParam.equipment.EquipmentID >= 3558 && api.pageParam.equipment.EquipmentID <= 3566) {
                                //     var url1 = 'http://' + APP.serverIP() + '/Frame/ST1_LLS/ZSRFIDHandler.aspx?cmd=submitData';
                                //     var url2 = 'http://' + APP.serverIP() + '/Frame/ST1_LLS/ZSRFIDHandler.aspx?cmd=pushBoxCode';

                                //     // 调用第一个接口
                                //     $.ajax({
                                //         url: url1,
                                //         type: 'GET',
                                //         contentType: 'application/json',
                                //         data: null,
                                //         success: function (data) {
                                //             console.log('成功:', data);


                                //         },
                                //         error: function (xhr, status, error) {
                                //             console.error('失败:', error);
                                //         }
                                //     });
                                // }
                            }
                            api.sendEvent({
                                name: 'refreshChoosePlan'
                            })
                        } else {
                            that.$dialog.confirm({
                                title: '提示',
                                message: res.ds[0].msg,
                                confirmButtonText: '确认上机'
                            })
                                .then(() => {
                                    that.clockIn()
                                })
                                .catch(() => {
                                });
                        }
                    })
                    that.correctedQuantitySS = 0;
                },

                pageBack() {
                    var that = this
                    if (window.localStorage.getItem('clientHeight') != 752) {
                        api.openFrame({
                            name: 'choosePlan',
                            url: 'choosePlan.html',
                            rect: {
                                x: 0,
                                y: 115,
                                w: api.winWidth,
                                h: api.winHeight - 150 - api.safeArea.bottom
                            },
                            bgColor: '#29292a',
                            pageParam: api.pageParam
                        })
                    } else {
                        api.openFrame({
                            name: 'choosePlan',
                            url: 'choosePlan.html',
                            rect: {
                                x: 0,
                                y: 170,
                                w: api.winWidth,
                                h: api.winHeight - 230 - api.safeArea.bottom
                            },
                            bgColor: '#29292a',
                            pageParam: api.pageParam
                        })
                    }

                },
                getFormatTime(date) {
                    var that = this
                    var seperator1 = "-";
                    var seperator2 = ":";
                    var month = date.getMonth() + 1;
                    var strDate = date.getDate();
                    var hour = date.getHours();
                    var minute = date.getMinutes();
                    var second = date.getSeconds();
                    if (month >= 1 && month <= 9) {
                        month = "0" + month;
                    }
                    if (strDate >= 0 && strDate <= 9) {
                        strDate = "0" + strDate;
                    }
                    if (hour >= 0 && hour <= 9) {
                        hour = "0" + hour;
                    }
                    if (minute >= 0 && minute <= 9) {
                        minute = "0" + minute;
                    }
                    if (second >= 0 && second <= 9) {
                        second = "0" + second;
                    }
                    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                        + " " + hour + seperator2 + minute
                        + seperator2 + second;
                    return currentdate;
                },
                getU8(table, btn) {
                    var that = this
                    if (that.showPrintMsg) {
                        var obj = {
                            ProductionNO: that.formData.ProductionNO,
                            ProductCode: table.ProductCode
                        }
                        APP.ajax('getZSU8MOID', obj, function (res) {
                            if (res.ds[0].status == 500) {
                                that.showPrintMsg = false
                                btn == 0 ? that.ifConfirm1 = false : that.ifConfirm2 = false

                                vm.$toast(res.ds[0].msg)
                            } else {
                                table.MoDID = res.ds[0].MoDID
                                table.MoID = res.ds[0].MoID
                                if (table.BaoZhangQTY) {
                                    that.getCodeData(table, btn)
                                } else {
                                    that.showPrintMsg = false
                                    btn == 0 ? that.ifConfirm1 = false : that.ifConfirm2 = false
                                    vm.$toast('包装数量为0, 请填写后再打印！');
                                    return false;
                                }
                            }
                        })
                    }
                },

                getCodeData(table, btn) {
                    var that = this
                    var obj
                    if (!that.TY) {
                        if (!that.formData.beforeEquipment) {
                            vm.$toast('请选择机台！');
                            that.showPrintMsg = false
                        }
                        if (!that.formData.beforeBatch) {
                            vm.$toast('请输入批次！');
                            that.showPrintMsg = false
                        }
                    }
                    if (that.showPrintMsg) {
                        if (that.totalPrint > 0) {
                            obj = {
                                ProductCode: table.ProductCode,
                                empolorName: window.localStorage.getItem('loginName'),
                                MONO: table.MONO,
                                Batch: that.formData.Batch,
                                MoID: table.MoID,
                                FBoxCode: '',
                                ZS_ZhuSuReporID: that.formData.reportID,
                                ProductID: table.ProductID,
                                MaxNumber: 1,
                                ZhuSuPlanDtlID: table.ZhuSuPlanDtlID,
                                WhetherStarteEquipment: that.formData.reportID ? 1 : 0,
                                LoginBatch: api.pageParam.currentBatch,
                                MoDID: table.MoDID,
                                ReporQTY: table.BaoZhangQTY,
                                ProductSpec: table.ProductSpec,
                                num: that.totalPrint,
                                ProductionNO: that.formData.ProductionNO,
                            }

                            APP.ajax('ZS_ReporPrintMany_TY3', obj, function (res) {
                                var data = res.ds1
                                data.sort(function (a, b) {
                                    return a.FBoxNum - b.FBoxNum
                                })
                                data.map((item) => {
                                    item.beforeEquipment = that.formData.beforeEquipment
                                    item.beforeBatch = that.formData.beforeBatch
                                })
                                // alert('多张'+JSON.stringify(data))
                                api.sendEvent({
                                    name: 'printStatus',  //打印多张
                                    extra: {
                                        totalCode: data,
                                    }
                                })

                                that.totalPrint = ''
                            })
                        } else {
                            obj = {
                                ProductSpec: table.ProductSpec,
                                ZS_ZhuSuReporID: that.formData.reportID,
                                ZhuSuPlanDtlID: table.ZhuSuPlanDtlID,
                                Batch: that.formData.Batch,
                                ProductCode: table.ProductCode,
                                MoID: table.MoID,
                                MoDID: table.MoDID,
                                ProductID: table.ProductID,
                                ReporQTY: table.BaoZhangQTY,
                                MONO: table.MONO,
                                WhetherStarteEquipment: that.formData.reportID ? 1 : 0,
                                empolorName: window.localStorage.getItem('loginName'),
                                MaxNumber: 1,
                                FBoxCode: '',
                                LoginBatch: api.pageParam.currentBatch,
                                ZBatch: that.formData.beforeBatch ? that.formData.beforeBatch : '',
                                ZFBoxNum: api.pageParam.beforeMsg.FBoxNum ? api.pageParam.beforeMsg.FBoxNum : 0,
                                TYXMCode: api.pageParam.beforeMsg.FBoxCode ? api.pageParam.beforeMsg.FBoxCode : '',
                                P_UserID: window.localStorage.getItem('loginName')
                            }
                            var API_URL = (that.autoPrintEnabled && !that.totalPrint)   // totalPrint>0 表示批量，批量仍走 TY3
                                ? 'ZS_ReporPrint_TY9'     // 自动打印
                                : 'ZS_ReporPrint_TY3';    // 手动/批量

                            if (that.autoPrintEnabled && !that.totalPrint) {

                                obj.LJSCNum = that.QuantitySS || 0;
                                obj.QSHM = that.QSHM || 0;
                                obj.SSHM = that.SSHM || 0;
                                obj.AutoPrint = 1;


                            }

                            APP.ajax(API_URL, obj, function (res) {  //打印单张
                                console.log('打印res' + JSON.stringify(res))
                                if (res.ds[0].status == 500) {
                                    that.showPrintMsg = false
                                    btn == 0 ? that.ifConfirm1 = false : that.ifConfirm2 = false
                                    vm.$dialog.confirm({
                                        message: res.ds[0].msg,
                                        confirmButtonText: '确认下机'
                                    })
                                        .then(() => {
                                            that.clockOut()
                                        })
                                        .catch(() => {
                                        });
                                } else if (res.ds[0].STATUS == 0) {
                                    // alert('箱码' + res.ds1[0].Column1)
                                    that.getPrint(table, res.ds1[0].Column1, res.ds3[0].MaxNumber, btn, res.ds2[0].GX)
                                }
                            })
                        }
                        that.getreport(table)
                    }
                },
                getreport(table) {
                    var that = this
                    if (that.showPrintMsg) {
                        var obj = {
                            ZS_ZhuSuReporID: that.formData.reportID,
                            ZhuSuPlanID: api.pageParam.ZhuSuPlanID,
                            ProductID: table.ProductID,
                            ProductionNO: that.formData.ProductionNO,
                        }
                        APP.ajax('ZS_TYReporRenewPlam', obj, function (res) {
                        })
                    }
                },
                getPrint(table, boxCode, number, btn, GX) {  //单张打印
                    var that = this
                    if (that.showPrintMsg) {
                        var code = {}
                        code.frontProductName = '产品名称：' + table.ProductName.slice(0, 10)
                        code.afterProductName = table.ProductName.length > 10 ? table.ProductName.slice(10, table.ProductName.length) : ''
                        code.boxCode = boxCode ? boxCode : ''
                        code.GX = '工序：' + GX ? GX : ''

                        that.printMsg = '标签正在打印...' //打印单张

                        if (!that.TY) { //涂油单张打印
                            api.toast({
                                msg: '涂油箱码已生成'
                            })
                            api.sendEvent({
                                name: 'refreshBrowser',
                                TY: false
                            })
                            api.closeFrame()
                        } else { //普通注塑机台打印
                            code.batch = '产品批次：' + that.formData.Batch
                            code.ProductCode = '产品编码：' + table.ProductCode
                            code.ProductionNO = '生产订单：' + that.formData.ProductionNO
                            code.date = '生产日期：' + that.getFormatTime(new Date()).split(' ')[0]
                            code.time = that.getFormatTime(new Date()).split(' ')[1]
                            code.BaoZhangQTY = '本箱数量：' + table.BaoZhangQTY + ' PCS'
                            that.formData.beforeEquipment ? code.EquipmentID = '设备编号：' + that.formData.beforeEquipment : code.EquipmentID = '设备编号：' + api.pageParam.equipment.EquipmentCode
                            code.EquipmentID = '设备编号：' + api.pageParam.equipment.EquipmentCode
                            code.empolorName = '操作员：' + window.localStorage.getItem('loginName')
                            code.lastBoxCode = '本箱序号：' + number
                            // alert('单张'+JSON.stringify(code))
                            api.sendEvent({
                                name: 'printStatus',
                                extra: {
                                    code: code,
                                }
                            })
                            // if (vm.printChainLock === 1) {
                            //     vm.printChainLock = 2;          
                            //     vm.ifConfirm1 = false;          
                            //     vm.printCode2('序号2');         
                            // }
                        }
                        console.log('成功打印1234')
                        setTimeout(() => {
                            that.currentPrinting = null;

                            // ===== 成对打印完成判断 =====
                            if (that.pairPrinting) {
                                if (that.pairSide === 1) {
                                    that.pairSide = 2;          // 下一步打右
                                    that.printPair();           // 立即打右
                                    return;                     // 不解锁，等右边
                                }
                                if (that.pairSide === 2) {
                                    // 一套完整结束
                                    that.pairPrinting = false;  // 允许下一套
                                    that.pairSide = 1;    // 重置左边
                                    vm.$toast('一套标签已打印完成');
                                }
                            }
                            // ============================

                            // 原有队列逻辑继续保留
                            if (that.printQueue.length > 0) {
                                var nextPrint = that.printQueue.shift();
                                if (nextPrint.type === 'print1') {
                                    that.printCode1(nextPrint.btn);
                                } else if (nextPrint.type === 'print2') {
                                    that.printCode2(nextPrint.btn);
                                }
                            }
                        }, 1000);
                    }
                },
                getBoxList() {
                    var that = this
                    if (that.formData.reportID && that.formData.reportID != "未上机") {
                        var obj = {
                            ZS_ZhuSuReporID: that.formData.reportID,
                            ZhuSuPlanID: that.formData.ZhuSuPlanID,
                            EquipmentID: api.pageParam.equipment.EquipmentID,
                        }
                        console.log('obj', JSON.stringify(obj))
                        APP.ajax('ZS_FoxboxList_TY', obj, function (res) {
                            console.log('ZS_FoxboxList_TY' + JSON.stringify(res))
                            res.ds.map((item) => {
                                item.FBoxCode = item.FBoxCode.split('-')[0]
                                item.ReporTime = item.ReporTime.split('T')[1]
                                item.ReporTime = item.ReporTime.split('.')[0]
                                item.checked = false
                            })
                            that.boxList = res.ds
                            that.boxListTotal = res.ds1[0].SUMReporQTY

                        })
                    }
                },
                getOver(table, btn) {
                    var that = this
                    if (that.showPrintMsg) {
                        if (table.BaoZhangQTY) {
                            APP.ajax('getZhuSuConfig', {}, function (res) {
                                if (res.ds[0].ISOverRepor) { //控制超报
                                    // 包装数量+(订单数量-订单欠数) <= 订单数量*(1+ %) 
                                    if (table.BaoZhangQTY > table.PlanQTY1 * (1 + res.ds[0].OverReporPercent) - (table.PlanQTY1 - table.PlanQianQTY)) {
                                        vm.$toast('报工超报，请重新填写！');
                                        that.showPrintMsg = false
                                        return false;
                                    } else {
                                        that.getU8(table, btn)
                                    }
                                } else {
                                    that.getU8(table, btn)
                                }
                            })
                        } else {
                            btn == 0 ? that.ifConfirm1 = false : that.ifConfirm2 = false
                            that.showPrintMsg = false
                            vm.$toast('包装数量为0，请重新填写后再打印！');
                            return false;
                        }
                    }
                },
                arrowLeftClick() {
                    var that = this
                    that.showBoxList = true
                    that.isBoxListOpen = true
                    if (that.autoPrintEnabled) {
                        that.stopAutoPrintInterval()
                    }
                    that.getBoxList()
                    that.boxListDelete = []
                },
                boxListChange(val) {
                    var that = this
                    if (val.checked) {
                        that.boxListDelete.push(val)
                    } else {
                        that.boxListDelete = that.boxListDelete.filter((item) => {
                            return item.checked == true
                        })
                    }
                },
                handlerDeleteBox() {
                    var that = this;
                    if (that.boxListDelete.length) {

                        (function deleteBoxes(index) {
                            if (index < that.boxListDelete.length) {
                                var item = that.boxListDelete[index];
                                var obj = {
                                    ZS_ZhuSuReporDtlID: item.ZS_ZhuSuReporDtlID,
                                    FBoxCode: item.FBoxCode,
                                };

                                APP.ajax('ZS_ZhuSuReporDel1', obj, function (res) {
                                    if (res && res.ds1[0].Column1) {
                                        var arr = {
                                            ProductID: res.ds1[0].ProductID
                                        };
                                        if (that.tableData.length === 1) {
                                            that.getreport(that.tableData[0]);
                                        } else if (that.tableData.length === 2) {
                                            that.getreport(that.tableData[0]);
                                            that.getreport(that.tableData[1]);
                                        }
                                        vm.$toast('箱码作废成功！');
                                        that.ALBarCodeNum = Math.max(0, that.ALBarCodeNum - 1);
                                        that.getBoxList();
                                        that.getList();


                                        deleteBoxes(index + 1);
                                    } else {

                                        vm.$dialog.confirm({
                                            message: '箱码作废失败，请重试！',
                                            confirmButtonText: '确认作废'
                                        }).then(() => {

                                            deleteBoxes(index);
                                        }).catch(() => {

                                        });
                                    }
                                });
                            }
                        })(0);
                    } else {
                        vm.$toast('请选择作废箱码！');
                    }
                },


                handlerBadReason() {
                    var that = this
                    api.sendEvent({
                        name: 'resetBreadList',
                        extra: {
                            breadData: {
                                name: '不良报废',
                                url: 'badReason',
                                ZS_FunctionID: 0,
                                click: true
                            }
                        }
                    })
                    if (window.localStorage.getItem('clientHeight') != 752) {
                        api.openFrame({
                            name: 'badReason',
                            url: 'badReason.html',
                            rect: {
                                x: 0,
                                y: 115,
                                w: api.winWidth,
                                h: api.winHeight - 150 - api.safeArea.bottom
                            },
                            bgColor: '#29292a',
                            pageParam: api.pageParam
                        })
                    } else {
                        api.openFrame({
                            name: 'badReason',
                            url: 'badReason.html',
                            rect: {
                                x: 0,
                                y: 170,
                                w: api.winWidth,
                                h: api.winHeight - 230 - api.safeArea.bottom
                            },
                            bgColor: '#29292a',
                            pageParam: api.pageParam
                        })
                    }
                },
                confirmTotalPrint() {
                    var that = this
                    if (that.totalPrint > 5) {
                        vm.$toast('批量打印数量必须小于5!!');
                        that.totalPrint = '';
                        return;
                    } else {
                        if (that.radio == '1') {
                            var obj = {
                                EquipmentID: api.pageParam.equipment.EquipmentID,
                                ProductID: that.tableData[0].ProductID,
                                ProductionNO: that.formData.ProductionNO
                            }
                            APP.ajax('IsPiLiang', obj, function (res) {
                                console.log('res', JSON.stringify(res))
                                if (res.ds[0].value) {
                                    that.printCode1('序号1')
                                } else {
                                    api.toast({
                                        msg: res.ds[0].msg
                                    })
                                }
                            })
                        } else {
                            var obj = {
                                EquipmentID: api.pageParam.equipment.EquipmentID,
                                ProductID: that.tableData[1].ProductID,
                                ProductionNO: that.formData.ProductionNO
                            }
                            APP.ajax('IsPiLiang', obj, function (res) {
                                console.log('res', JSON.stringify(res))
                                if (res.ds[0].value) {
                                    that.printCode2('序号2')
                                } else {
                                    api.toast({
                                        msg: res.ds[0].msg
                                    })
                                }
                            })
                        }
                    }
                },
                handlerPrintAgain() {
                    var that = this
                    if (that.boxListDelete.length == 1) {
                        that.showPrintMsg = true
                        that.boxListDelete.map((item) => {
                            var obj = {
                                ZS_ZhuSuReporDtlID: item.ZS_ZhuSuReporDtlID,
                            }
                            APP.ajax('ZS_PrintAgain', obj, function (res) {
                                res.ds[0].ProductCode = res.ds[0].ProductCODE
                                res.ds[0].BaoZhangQTY = res.ds[0].ReporQTY
                                that.getPrint(res.ds[0], res.ds[0].FBoxCode, res.ds[0].FBoxNum)
                                that.boxListDelete = []
                            })
                        })
                    } else if (that.boxListDelete.length > 1) {
                        that.showPrintMsg = true
                        var obj = {
                            ZS_ZhuSuReporDtlID: that.boxListDelete.map((item) => item.ZS_ZhuSuReporDtlID).join(','),
                        }
                        APP.ajax('ZS_PrintAgain2', obj, function (res) {
                            var data = res.ds
                            data.sort(function (a, b) {
                                return a.FBoxNum - b.FBoxNum
                            })
                            // alert('补打'+JSON.stringify(data))
                            api.sendEvent({
                                name: 'printStatus',   //单/多张补打
                                extra: {
                                    totalCode: data,
                                }
                            })
                            that.boxListDelete = []
                        })
                    } else {
                        vm.$toast('请选择补打标签！');
                    }
                },
                handlerESOP(item, index) {
                    api.pageParam.ProductItem = item
                    var that = this
                    api.openWin({
                        name: 'ESOP',
                        url: 'ESOP.html',
                        bgColor: '#29292a',
                        pageParam: api.pageParam
                    })
                },
                toBroke() {
                    var that = this
                    var obj = {
                        FaultName: '',
                        BillDate: APP.getFormatDate(new Date()),
                        EquipmentID: api.pageParam.equipment.EquipmentID,
                        FaultTypeID: '',
                        Declarer: window.localStorage.getItem('pin'),
                        Notifier: '',
                        Comment: ''
                    }
                    console.log('obj', JSON.stringify(obj))
                    APP.ajax('ZS_SubmitFaultDoc', obj, function (res) {
                        console.log('res', JSON.stringify(res))
                        if (res.ds[0]) {
                            vm.$toast('故障呼叫成功！');
                        } else {
                            vm.$toast('故障呼叫失败，请重试！');
                        }
                    })
                }
            }
        })
    };
</script>

</html>